package com.xjscrm.server.service.grouppulljob.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.operatorplandevice.OperatorPlanDeviceRule;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.common.util.SleepTimeTools;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.service.grouppulljob.GroupPullJobService;
import com.xjscrm.server.service.grouppulljob.GroupPullMsgService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 拉群任务异步实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class GroupPullJobServiceImpl implements GroupPullJobService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private GroupPullTaskMapper groupPullTaskMapper;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private GroupPullMsgService groupPullMsgService;
    @Autowired
    private GroupPullJobDeviceMapper groupPullJobDeviceMapper;
    @Autowired
    private GroupPullJobMapper groupPullJobMapper;
    @Autowired
    private GroupPullTaskDeviceMapper groupPullTaskDeviceMapper;
    @Autowired
    private GroupPullTaskDeviceConfigMapper groupPullTaskDeviceConfigMapper;


    /**
     * 创建拉群数据
     *
     * @param groupPullTask
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    public void addGroupPullJob(GroupPullTask groupPullTask){
        try {
            if (groupPullTask == null) {
                throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "拉群任务不存在");
            }

            int now = DateUtil.getTime();

            //新建拉群消息
            GroupPullJob groupPullJob = new GroupPullJob();
            groupPullJob.setId(IdWorker.getId());
            groupPullJob.setMerId(groupPullTask.getMerId());
            groupPullJob.setTaskId(groupPullTask.getId());
            groupPullJob.setName(groupPullTask.getName());
            groupPullJob.setType(groupPullTask.getType());
            groupPullJob.setSendTime(groupPullTask.getSendTime());
            groupPullJob.setTime(groupPullTask.getTime());
            groupPullJob.setWeek(groupPullTask.getWeek());
            groupPullJob.setDay(groupPullTask.getDay());
            groupPullJob.setCustomerType(groupPullTask.getCustomerType());
            groupPullJob.setCustomerEnterpriseTagOpt(groupPullTask.getCustomerEnterpriseTagOpt());
            groupPullJob.setCustomerEnterpriseTags(groupPullTask.getCustomerEnterpriseTags());
            groupPullJob.setCustomerCreateDayStart(groupPullTask.getCustomerCreateDayStart());
            groupPullJob.setCustomerCreateDayEnd(groupPullTask.getCustomerCreateDayEnd());
            groupPullJob.setCustomerRemarkOpt(groupPullTask.getCustomerRemarkOpt());
            groupPullJob.setCustomerGenders(groupPullTask.getCustomerGenders());
            groupPullJob.setRule(groupPullTask.getRule());
            groupPullJob.setGuiderSwtich(groupPullTask.getGuiderSwtich());
            groupPullJob.setGuider(groupPullTask.getGuider());
            groupPullJob.setStatus(groupPullTask.getStatus());
            groupPullJob.setStartSendTime(groupPullTask.getHanderTime());
            groupPullJob.setCreateTime(now);
            groupPullJob.setUpdateTime(now);
            groupPullJob.setExcludeCustomerEnterpriseTagOpt(groupPullTask.getExcludeCustomerEnterpriseTagOpt());
            groupPullJob.setExcludeCustomerEnterpriseTags(groupPullTask.getExcludeCustomerEnterpriseTags());
            groupPullJob.setExcludeNewCustomer(groupPullTask.getExcludeNewCustomer());
            groupPullJob.setExcludeCustomerCreateDayStart(groupPullTask.getExcludeCustomerCreateDayStart());
            groupPullJob.setExcludeCustomerCreateDayEnd(groupPullTask.getExcludeCustomerCreateDayEnd());
            groupPullJob.setExcludeCustomerGenders(groupPullTask.getExcludeCustomerGenders());
            groupPullJob.setExcludeCustomerRemarkOpt(groupPullTask.getExcludeCustomerRemarkOpt());
            groupPullJob.setOpenExclude(groupPullTask.getOpenExclude());
            groupPullJobMapper.insertSelective(groupPullJob);

            //添加机器人表
            List<GroupPullTaskDevice> groupPullTaskDevices = groupPullTaskDeviceMapper.selectListByTaskId(groupPullTask.getId(), groupPullTask.getMerId());
            if(groupPullTaskDevices != null && groupPullTaskDevices.size() > 0){
                for (GroupPullTaskDevice groupPullTaskDevice : groupPullTaskDevices) {
                    //查询该机器人发送设置
                    GroupPullTaskDeviceConfig groupPullTaskDeviceConfig = groupPullTaskDeviceConfigMapper.selectByDeviceUniqueId(groupPullTaskDevice.getDeviceUniqueId(), groupPullTaskDevice.getMerId());
                    if(groupPullTaskDeviceConfig == null){
                        groupPullTaskDeviceConfig = new GroupPullTaskDeviceConfig();
                    }

                    //查询该机器人存不存在
                    WwDevice wwDevice = wwDeviceMapper.queryById(groupPullTaskDevice.getDeviceUniqueId());
                    if(wwDevice == null){ //不存在，则跳出
                        continue;
                    }

                    GroupPullJobDevice groupPullJobDevice = new GroupPullJobDevice();
                    groupPullJobDevice.setId(IdWorker.getId());
                    groupPullJobDevice.setMerId(groupPullTaskDevice.getMerId());
                    groupPullJobDevice.setJobId(groupPullJob.getId());
                    groupPullJobDevice.setDeviceUniqueId(groupPullTaskDevice.getDeviceUniqueId());
                    groupPullJobDevice.setDeviceId(wwDevice.getDeviceId());
                    groupPullJobDevice.setRateMin(Tools.getInteger(groupPullTaskDeviceConfig.getRateMin()));
                    groupPullJobDevice.setRateMax(Tools.getInteger(groupPullTaskDeviceConfig.getRateMax()));
                    groupPullJobDevice.setRule(groupPullTaskDeviceConfig.getRule());
                    groupPullJobDevice.setDelaySnapshot(0); //默认快照为0
                    groupPullJobDevice.setCreateTime(now);
                    groupPullJobDevice.setUpdateTime(now);
                    groupPullJobDeviceMapper.insertSelective(groupPullJobDevice);

                    //封装该机器人发送消息
                    groupPullMsgService.addGroupPullMsg(groupPullJob.getMerId(), groupPullJob, groupPullJobDevice);

                }
            }
        }catch (Exception e){
            log.error(e.getMessage(), e);
        }

    }

    /**
     * 处理该任务的拉群数据
     *
     * @param groupPullJob
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    public void groupPullJobSendData(GroupPullJob groupPullJob){
        if (groupPullJob == null) {
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "拉群任务不存在");
        }

        //查询该任务涉及机器人列表
        List<GroupPullJobDevice> groupPullJobDeviceList = groupPullJobDeviceMapper.selectByJobId(groupPullJob.getId(), groupPullJob.getMerId());
        if(groupPullJobDeviceList != null && groupPullJobDeviceList.size() > 0){
            for (GroupPullJobDevice groupPullJobDevice : groupPullJobDeviceList) {
                try {

                    //限制是否休眠
                    OperatorPlanDeviceRule operatorPlanDeviceRule = JSONObject.parseObject(groupPullJobDevice.getRule(), OperatorPlanDeviceRule.class);
                    boolean sleepFlag = SleepTimeTools.verifySleepTime(operatorPlanDeviceRule);
                    if(!sleepFlag){
                        groupPullMsgService.groupPullJobMsgToMqSync(groupPullJob.getMerId(), groupPullJob, groupPullJobDevice);
                    }
                }catch (Exception e){
                    log.error("处理拉群任务的拉群消息出错，error={}",e.getMessage(), e);
                }

            }
        }

    }


}
